package cn.dai.controller.api;

import cn.dai.pojo.TokenDataDto;
import cn.dai.util.TokenUtil;
import cn.dai.exception.TokenAuthException;
import cn.dai.pojo.ReturnCode;
import cn.dai.pojo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author daijiyong
 */
@Slf4j
@RestController
@RequestMapping("/api/wechat/token")
public class TokenController {

    @RequestMapping(path = "/getToken", method = RequestMethod.POST)
    public TokenDataDto getToken(TokenVo tokenVo) throws TokenAuthException {
        log.info("请求token参数：{}", tokenVo);
        TokenUtil.getToken(tokenVo);
        return new TokenDataDto(tokenVo);
    }

    @RequestMapping(path = "/refreshToken", method = RequestMethod.POST)
    public TokenDataDto refreshToken(HttpServletRequest request) throws TokenAuthException {
        String token = request.getHeader(TokenUtil.REQUEST_HEADER_TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            throw new TokenAuthException(ReturnCode.INVALID_TOKEN);
        }
        TokenVo tokenVo = TokenUtil.parseToken(token);
        long timeOfUse = System.currentTimeMillis() - tokenVo.getTimestamp();
        //判断 token 是否过期
        if (timeOfUse > TokenUtil.oldToken) {
            throw new TokenAuthException(ReturnCode.INVALID_TOKEN);
        }
        TokenUtil.getToken(tokenVo);
        return new TokenDataDto(tokenVo);
    }
}
